package com.dhq.myapp

import android.annotation.SuppressLint
import android.bluetooth.BluetoothDevice
import android.content.Context
import android.util.Log
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import com.dhq.myapp.base.BaseActivity
import androidx.recyclerview.widget.RecyclerView
import com.dhq.myapp.base.adapter.RvBaseAdapter
import com.dhq.myapp.base.adapter.RvBaseHolder
import com.dhq.myapp.base.divider.DividerFactory
import com.dhq.myapp.entity.DeviceConnectEvent
import com.dhq.myapp.util.BluetoothHelper
import com.dhq.myapp.util.CXRUtil
import com.dhq.myapp.util.DataStorageUtils
import com.dhq.myapp.util.GlassOptionUtil
import com.rokid.cxr.client.extend.CxrApi
import com.rokid.cxr.client.extend.callbacks.BluetoothStatusCallback
import com.rokid.cxr.client.utils.ValueUtil
import org.greenrobot.eventbus.EventBus

/**
 * DESC
 * Created by DHQ on 2025/10/12.
 */
class BluetoothScanActivity : BaseActivity() {

    private var rv_bluetooth_list: RecyclerView? = null;
    private var mAdapter:RvBaseAdapter<BluetoothDevice>?=null;
    private var bluetoothHelper: BluetoothHelper? = null
    private var mCXRUtil: CXRUtil? = null
    private var tv_status: TextView? = null


    override fun getLayoutId(): Int {
        return R.layout.activity_bluetooth_scan_lay
    }

    override fun initView() {
        tv_status = findViewById<TextView>(R.id.tv_status)
        rv_bluetooth_list = findViewById<RecyclerView>(R.id.rv_bluetooth_list)
        rv_bluetooth_list?.layoutManager = LinearLayoutManager(this)
        DividerFactory.builder(this).setSpaceColor(R.color.color_gray,R.dimen.dp750_2).buildLinearDivider().addTo(
            rv_bluetooth_list!!
        )
        mAdapter = object :RvBaseAdapter<BluetoothDevice>(R.layout.item_bluetooth_lay){
            @SuppressLint("MissingPermission")
            override fun convert(
                adapter: RvBaseAdapter<BluetoothDevice>,
                holder: RvBaseHolder,
                item: BluetoothDevice,
                position: Int
            ) {
                holder.setText(R.id.tv_bluetooth_name,item.name+"--"+item.uuids.toString())
                holder.setText(R.id.tv_bluetooth_mac,item.address)
//                var uuids = item.uuids.toString();

                holder.getRootView().setOnClickListener(object : View.OnClickListener{
                    override fun onClick(view: View?) {
                        connectDevice(item)
                    }

                })
            }

        }
        rv_bluetooth_list?.adapter = mAdapter
    }

    override fun initData() {

        getHeaderUtil().setHeaderTitle("扫描设备")
        init();
        mCXRUtil=CXRUtil(object :CXRUtil.ConnectListener{
            override fun onConnected() {
                tv_status?.setText("连接成功");
            }

            override fun onDisconnected() {
                tv_status?.setText("连接断开");
            }

            override fun onFailed() {
                tv_status?.setText("连接失败");
            }
        });
        bluetoothHelper?.permissionResult?.postValue(true)
        bluetoothHelper?.checkPermissions()
    }


    fun init() {
        // 创建BluetoothHelper实例
        bluetoothHelper = BluetoothHelper(this, { initStatus ->
            // 处理初始化状态回调
            when (initStatus) {
                BluetoothHelper.Companion.INIT_STATUS.NotStart -> {
//                        Toast.makeText(this, "Bluetooth initialization not started", Toast.LENGTH_SHORT).show()
                }

                BluetoothHelper.Companion.INIT_STATUS.INITING -> {
                    Toast.makeText(this, "蓝牙初始化中", Toast.LENGTH_SHORT).show()
                }

                BluetoothHelper.Companion.INIT_STATUS.INIT_END -> {
                    Toast.makeText(this, "蓝牙初始化完成", Toast.LENGTH_SHORT).show()
                    // 初始化完成后可以开始扫描设备

                    scanDevices()
                    // bluetoothHelper?.startScan() // 注意：startScan()已经在BluetoothHelper内部调用
                }
            }
        }, {
            // 处理设备发现回调
//            Toast.makeText(this, "发现新设备", Toast.LENGTH_SHORT).show()
            // 可以在这里更新UI，显示发现的设备
//                updateDeviceList()


        })

        bluetoothHelper?.setScanListener(object : BluetoothHelper.BluetoothListener{
            @SuppressLint("MissingPermission")
            override fun deviceFound(device: BluetoothDevice) {
                Log.e("设备",device.name)
                addDevice(device)
            }
        })


    }

    fun addDevice(device: BluetoothDevice){
        var list = mAdapter?.getDatas();
        val hasAlice = list?.any { it.address == device.address }
        if (hasAlice != true){
            mAdapter?.addData(device)
        }
    }

    /**
     * 连接设备
     */
    fun connectDevice(device: BluetoothDevice){
        tv_status?.setText("连接中。。。");

        connectRokid(this,device);

//        mCXRUtil?.initDevice(this@BluetoothScanActivity,device);
    }

    /**
     * 手动开始扫描设备
     */
    @SuppressLint("MissingPermission")
    fun scanDevices() {
        bluetoothHelper?.startScan()
    }

    /**
     * 停止扫描设备
     */
    @SuppressLint("MissingPermission")
    fun stopScanDevices() {
        bluetoothHelper?.stopScan()
    }


    override fun onDestroy() {
        super.onDestroy()
        // 释放BluetoothHelper资源
        bluetoothHelper?.release()
    }



    private fun connectRokid(context: Context, device: BluetoothDevice) {
        var socketUuid1 ="";
        var macAddress2 ="";
        CxrApi.getInstance().initBluetooth(context, device, object : BluetoothStatusCallback {


            override fun onConnectionInfo(
                socketUuid: String?, macAddress: String?, rokidAccount: String?, glassesType: Int
            ) {
                if (socketUuid != null && macAddress != null) {
                    socketUuid1 = socketUuid
                    macAddress2 = macAddress
                    CxrApi.getInstance().connectBluetooth(context, socketUuid, macAddress, this)
                }
            }
            @SuppressLint("MissingPermission")
            override fun onConnected() {
                Log.d("BluetoothScanActivity", "Connected")
                runOnUiThread {
                    DataStorageUtils.putObject("socketUuid",socketUuid1)
                    DataStorageUtils.putObject("macAddress",macAddress2)
                    DataStorageUtils.putObject("bluetoothName",device.name)

                    EventBus.getDefault().post(DeviceConnectEvent(device))
                    tv_status?.setText("连接成功");
                }
            }
            override fun onDisconnected() {
                Log.d("BluetoothScanActivity", "Disconnected")
                runOnUiThread {
                    tv_status?.setText("连接断开");
//                    tvStatus.text = "设备已断开连接"
//                    btnSend.isEnabled = false
//                    btnScan.text = "重新扫描"
//                    btnScan.isEnabled = true
                }
            }
            override fun onFailed(code: ValueUtil.CxrBluetoothErrorCode?) {
                Log.e("BluetoothScanActivity", "Failed: ${code}")
                runOnUiThread {
                    tv_status?.setText("连接失败");
//                    tvStatus.text = "连接失败: $code"
//                    btnSend.isEnabled = false
//                    btnScan.text = "重新扫描"
//                    btnScan.isEnabled = true
                }
            }
        })
    }

}